<template>
  <div>
    <el-form label-width="100px" style="width:100%;">
      <!-- 规格表单 -->
      <div class="selecter">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品规格">
              <div class="add-form" @click="showModelDialog"><i class="el-icon-plus"></i>添加规格</div>
            </el-form-item>
            <el-dialog title="商品规格项目" :visible.sync="visibleModelDialog" width="30%">
              <el-row>
                <el-col>
                  <h4>常用规格</h4>
                  <div @click="checkGoodsModel" style="text-align:center;">
                    <el-checkbox-group
                      v-model="checkedModels" :max="1">
                      <el-checkbox class="goods-model-item"
                                   v-for="(model, index) in commonModels"
                                   :label="model" :key="index" border size="mini"
                      >{{model}}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                  <div style="margin-top:10px;">
                    <span style="color:#409EFF;margin:0 10px;">已选：</span>{{checkedModels.join('，')}}
                  </div>
                </el-col>
              </el-row>
              <div class="button-group__right">
                <el-button type="default" @click="visibleModelDialog = false">取消</el-button>
                <el-button type="primary" @click="confirmGoodsModel">确定</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <div v-if="(checkedModels.length > 0)" v-for="(modelItem, index) in selectModels" :key="index">
              <div class="model-item">
                <div class="model-name">
                  {{modelItem.name}}
                  <i class="el-icon-close" @click="delModelItem(modelItem.name)"></i>
                </div>
                <div class="sub-model-wrap">
                  <input-box v-for="(item, indey) in modelItem.info" :key="indey"
                             @edit="editSubModel"
                             @cancel="cancelSubModelItem(modelItem)"
                             @delete="delSubModel"
                             :index="indey" :target="modelItem" :content="item.name"
                             @blur="editSubModel">
                  </input-box>
                  <div class="add-form"
                       v-show="!modelItem.isInputSubModel"
                       @click="addSubModel(modelItem)"
                  >
                    <i class="el-icon-plus"></i>添加标签
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <avue-crud :data="tableList" :option="modifyOption" @row-update="saveData">

        <template slot-scope="scope" slot="typeName0">
          <span>{{scope.row.typeName0.name}}</span>
        </template>

        <template slot-scope="scope" slot="typeName1">
          <span>{{scope.row.typeName1.name}}</span>
        </template>

        <template slot-scope="scope" slot="typeName2">
          <span>{{scope.row.typeName2.name}}</span>
        </template>
        <template slot-scope="scope" slot="modelUrl">
          <img v-if="scope.row.modelUrl"
               @click="sel_img(scope.$index, scope.row)"
               :src="scope.row.modelUrl"
               style="width:100%;height:100%;">
          <div class="select_img" v-else @click="sel_img(scope.$index, scope.row)"><i class="el-icon-plus"></i></div>
          <el-dialog title="选择图片" :visible.sync="sleImg" style="text-align: left;">
            <sel-img-photogallery ref="selImg" type="03" @select="onSelectImgs"></sel-img-photogallery>
          </el-dialog>
        </template>
      </avue-crud>
    </el-form>
  </div>
</template>

<script>
  import dictionary from './../../../util/pds/dictionary'
  import {modelGoodsOption} from '../../../const/crud/supply/supplierEdit'
  import selImgPhotogallery from '@/components/pds/common/sel_img_photogallery'
  import {deepClone} from "../../../util/util";

  export default {
    name: "newGoodsSelecter",
    components: {
      selImgPhotogallery
    },
    props: {
      goodsInfo: {
        type: Object,
        default() {
          return {}
        }
      },
      modelList: {
        type: Array,
        default() {
          return []
        }
      },
      attrMap: {
        type: Object,
        default() {
          return {};
        }
      }
    },
    data() {
      return {

        sleImg: false,
        tableData: [],
        tableoption: modelGoodsOption,
        visibleModelDialog: false,
        //选择的规格名称
        checkedModels: [],
        commonModels: dictionary.commonModels,
        // 添加的标签栏
        selectModels: [],
        typeName: [],
        modelName: [],
        modifyOption: {},
        tableList: []
      }
    },
    watch: {
      attrMap: function (newVal, oldVal) {
        newVal && this.initAttrMap(this.attrMap)
      },
      modelList: function (newVal, oldVal) {
        newVal && this.initData(this.modelList)
      },
      // "selectModels": {
      //   handler: function (val,oldVal) {
      //     console.log(val);
      //     console.log(oldVal);
      //   },
      //   deep:true
      // }

    },
    created() {

      if (this.attrMap.length != 0) {
        this.initAttrMap(this.attrMap)
      }
      if (this.modelList.length != 0) {
        this.initData(this.modelList)
      }
      // console.log(this.commonModels);
    },
    methods: {
      //选择图片
      sel_img(index, row) {
        this.sleImg = true;
        this.imgIndex = index;
      },
      onSelectImgs(imgs) {
        this.modelList[this.imgIndex].modelUrl = imgs[0].picUrl;
        this.sleImg = false;
      },
      showModelDialog() {
        this.visibleModelDialog = true
      },
      initData(data) {
        // this.typeName = data[0].typeName.split(",")
        data.forEach(itemFirst => {
          console.log(itemFirst);
          let modelItem = itemFirst.modelName.split(',')
          itemFirst.typeName0 = ''
          itemFirst.typeName1 = ''
          itemFirst.typeName2 = ''
          // console.log(modelItem);
          modelItem.forEach((item, index) => {
            let typeName = ''
            if (index == 0) {
              typeName = "typeName0"
              // itemFirst.typeName0 = item
            }
            if (index == 1) {
              typeName = "typeName1"
              // itemFirst.typeName1 = item
            }
            if (index == 2) {
              typeName = "typeName2"
              // itemFirst.typeName2 = item
            }
            let arr = this.selectModels[index].info
            for (let i = 0; i < arr.length; i++) {
              if (arr[i].name == item) {
                itemFirst[typeName] = arr[i]
                break;
              }
            }

          })
        })
        // console.log(data);
        this.tableList = data
        this.initOption(this.tableoption)
      },
      initOption(option) {
        this.modifyOption = deepClone(this.tableoption);
        for (let i = 0; i < this.typeName.length; i++) {
          this.modifyOption.column[i].label = this.typeName[i]
          this.modifyOption.column[i].hide = false
        }

      },
      //展示上屏规格
      initAttrMap(goodsInfo) {
        // goodsInfo.forEach(item => {
        //   console.log(item);
        // })
        for (let item in goodsInfo) {
          this.typeName.push(item)
          this.checkedModels.push(item)
          let typeModels = {}
          typeModels.name = item
          typeModels.info = []
          // console.log(goodsInfo[item]);
          for (let type in goodsInfo[item]) {
            typeModels.info.push({name: goodsInfo[item][type]})
          }
          this.selectModels.unshift(typeModels)
        }
        console.log(this.selectModels);
      },
      checkGoodsModel(e) {
        let length = this.checkedModels.length
        let checked = this.checkedModels.indexOf(e.target.defaultValue) > 0
        if (e.target.localName == 'input' && length == 3 && !checked) {
          this.$message({
            showClose: true,
            message: '规格最多选择3项。',
            type: 'warning'
          })
        }
      },
      /**
       *  添加规格标签, 规格标签id从30开始递增(不连续)
       *  subModelLength记录标签历史最多数量
       *  isInputSubModel 在新增标签后为true, 隐藏添加按钮
       */
      addSubModel(modelItem) {
        console.log(modelItem);
        let name = {
          name: ''
        }
        modelItem.info.push(name)
        let len = modelItem.info.length - 1
        let modelName = []
        let modelNames = []
        this.selectModels.forEach((item, index) => {
          if (item.name == modelItem.name) {
            modelName[index] = this.selectModels[index].info[len].name

          } else {
            if (item.name != modelItem.name) {
              this.selectModels[index].info.forEach((item, indey) => {
                modelNames.push(item.name)
              })
            }
          }
        })
        let arr = this.combine(modelNames, modelName)
        // console.log(this.selectModels);
        // console.log(this.checkedModels);
        if (arr == false) {
          let typeName = modelName[0]
          console.log(typeName);
          const tableItem = {
            modelName: typeName,
            typeName: this.checkedModels[0] ,
            modelPrice: this.goodsInfo.marketPrice,
            modelUrl: this.goodsInfo.thumbUrl,
            modelUnit: this.goodsInfo.unit,
            modelStorage: this.goodsInfo.storage,
            stocksForewarn: '',
            modelCode: '',
            costPrice: '',
            weight: '',
            volume: ''
          }
          this.tableList.push(tableItem)
          console.log(this.tableList);
        } else {
          arr.forEach(item => {
            let typeName = item.join()
            const tableItem = {
              modelName: typeName,
              typeName: this.modelList[0].typeName,
              modelPrice: this.goodsInfo.marketPrice,
              modelUrl: this.goodsInfo.thumbUrl,
              modelUnit: this.goodsInfo.unit,
              modelStorage: this.goodsInfo.storage,
              virtualPrice: this.goodsInfo.virtualPrice,
              stocksForewarn: '',
              modelCode: '',
              costPrice: '',
              weight: '',
              volume: ''
            }
            this.tableList.push(tableItem)
          })
        }

      },
      /**
       * 监听 checkedModels 时调用, 生成selectModels =>
       *  {
       *      '1': { id: 1, name: '尺码', subModelId: [], subModelName: []}
       *  }
       *  isInputSubModel 用于标示是否隐藏‘添加标签’按钮
       */
      genModels(val, oldVal) {
        let that = this
        if (!Array.isArray(val)) {
          console.log('genModels参数错误');
          return;
        }

        let models = {}
        val.map((item, index) => {
          let id = that.commonModels.indexOf(item) + 1
          // if (!oldVal.indexOf(item) && (that.selectModels[id] == null)) {
          models[id] = {
            id: id,
            name: item,
            subModelName: [],
            subModelId: [],
            isInputSubModel: false
          }
          // } else {
          //     models[id] = that.selectModels[id]
          // }
        })
        that.selectModels = models
      },
      /**
       * 确认选择规格类型(颜色,尺寸等), 选择的类型会放入checkedModels(array)
       * 通过 Vue的 watcher 监听 checkedModels 有变化时调用 genModels 生成商品的规格选项
       */
      confirmGoodsModel(e) {
        if (this.checkedModels.length < 1) {
          this.$message({
            showClose: true,
            message: '请选择规格',
            type: 'warning'
          })
          return;
        }
        let model = {
          name: this.checkedModels[0],
          info: []
        }
        console.log(model);
        this.selectModels[0] = model

        // 说明: 根据选中的规格动态生成model对象
        // this.genModels(this.checkedModels);

        // 关闭对话框
        this.visibleModelDialog = false
      },
      // 删除规格类型, 如: 颜色, 尺寸等
      delModelItem(name) {
        let models = this.checkedModels

        this.selectModels.pop()
        models.pop()
        console.log(this.selectModels);
        console.log(this.checkedModels);
        const len = this.tableList.length
        for(let i=0;i<len;i++){
          this.tableList.pop()
        }

      },
      // 绑定inputBox@edit 点击‘铅笔’时进入编辑状态
      editSubModel(data) {
        console.log(data);
        let content = data.content
        this.tableList[data.index].modelName = content
        data.target.info[data.index].name = content
        console.log(this.tableList);
      },
      // 绑定inputBox@cancel 在inputBox没有值, 点击x时调用, 删除规格标签
      cancelSubModelItem(modelItem) {
        modelItem.info.pop()
        this.tableList.pop()
        modelItem.isInputSubModel = false
        // console.log("cancel ", modelItem);
      },
      delSubModel(data) {
        console.log(data);
        data.target.info.splice(data.index,1)
        this.tableList.splice(data.index,1)
        // let modelItem = data.target
        // let index = data.index
        // // console.log("del", data);
        // modelItem.isInputSubModel = false
        // this.subModelLength--;
        // let s_name = modelItem.subModelName[index];
        // // 删除 规格标签信息
        // let s_id_array = [];
        // let s_name_array = [];
        // let cur_s_id = 29;
        // modelItem.subModelName.forEach((item, index) => {
        //   cur_s_id++;
        //   if (s_name === item) {
        //     cur_s_id--;
        //   } else {
        //     s_id_array.push(cur_s_id);
        //     s_name_array.push(item);
        //   }
        // });
        // modelItem.subModelId = s_id_array;
        // modelItem.subModelName = s_name_array;
        // console.log("del selectModels", this.selectModels);
        // console.log("del modelItem", modelItem);
      },
      saveData(from, index, done, loading) {
        console.log(index);
        loading()
        done()
        console.log(from);
      },
      /**
       *  生成规格组合(笛卡尔积)
       *  参数为多个数组, combine([1, 3], ['a', 'b']) => [[1, "a"], [1, "b"],[3, "a"],[3, "b"]]
       *  特殊用法: 使用apply调用, 如: this.combine.apply(this.combine, [[1, 3], ['a', 'b']])
       *  特殊用法: 使用call调用, 如: this.combine.apply(this.combine, [1, 3], ['a', 'b'])
       *  方便在有未知个参数时使用.
       */
      combine() {
        return Array.prototype.reduce.call(arguments, function (a, b) {
          var ret = [];
          a.forEach(function (a) {
            b.forEach(function (b) {
              ret.push(a.concat([b]));
            });
          });
          return ret;
        }, [[]]);
      },

    }
  }
</script>

<style scoped>
  .select_img {
    width: 50px;
    height: 50px;
    line-height: 50px;
    border: 1px dashed #c0ccda;
    background-color: #fbfdff;
    font-size: 18px;
    color: #8c939d;
    cursor: pointer;
    border-radius: 6px;
    margin: 0 auto;
  }

  .goods-info-wrap {
    padding: 0 20px;
  }

  /* 标题 */
  .item-title {
    margin-top: 15px;
    margin-bottom: 24px;
    padding-bottom: 10px;
    font-size: 14px;
    line-height: 16px;
    border-bottom: 1px solid #e9e9e9;
  }

  .item-title span {
    display: block;
    padding-left: 10px;
    margin-right: 5px;
    border-left: 3px solid #5491de;
  }

  .item-title-tips {
    display: inline-block;
    margin-left: 10px;
    color: #999999;
    font-size: 12px;
  }

  .picturePreviewDialog {
    margin: auto;
    width: 50%;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
  }

  .goods-form-input {
    width: 286px;
    margin-right: 10px;
  }

  .goods-category {
    border: 1px solid #e9e9e9;
    margin-top: 10px;
    width: 286px;
    border-radius: 3px;
    max-height: 200px;
    overflow: scroll;
  }

  .add-form {
    width: 80px;
    padding-left: 5px;
    border: 1px dashed #e9e9e9;
    border-radius: 3px;
    font-size: 14px;
  }

  .add-model {
    display: inline-block;
    padding: 3px 10px 3px 10px;
    border: 1px dashed #e9e9e9;
    border-radius: 3px;
    color: #606266;
    font-size: 12px;
    margin-top: 10px;
    margin-bottom: 20px;
  }

  .button-group__center {
    margin-top: 20px;
    text-align: center;
  }

  .button-group__right {
    margin-top: 20px;
    margin-right: 10px;
    text-align: right;
  }

  /* 规格相关 */
  .goods-model-item {
    margin: 10px;
  }

  .model-item {
    display: flex;
    align-items: center;
    margin: 20px;
  }

  .model-name {
    box-sizing: border-box;
    height: 32px;
    font-size: 14px;
    padding: 5px 15px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
  }

  .model-name i {
    margin-left: 10px;
  }

  .sub-model-wrap {
    position: relative;
    display: inline-block;
    width: 50%;
    margin-left: 30px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
    padding: 10px;
  }

  .sub-model-wrap::before {
    content: '';
    display: block;
    position: absolute;
    top: 50%;
    margin-top: -12px;
    left: -12px;
    border-bottom: 12px solid transparent;
    border-top: 12px solid transparent;
    border-right: 12px solid #dcdfe6;
  }

  .sub-model-wrap::after {
    content: '';
    display: block;
    position: absolute;
    left: -10px;
    top: 50%;
    margin-top: -12px;
    border-bottom: 12px solid transparent;
    border-top: 12px solid transparent;
    border-right: 12px solid #fff;
  }

  .sub-model-wrap .add-form {
    display: inline-block;
    padding-top: 5px;
    padding-bottom: 5px;
  }

  .sub-model-item {
    display: inline-block;
  }

  .sub-model-item i {
    font-weight: bold;
  }

  .sub-model-item__confirm {
    display: inline-block;
    height: 32px;
    line-height: 30px;
    padding: 0px 10px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
    font-size: 14px;
    box-sizing: border-box;
  }

  /* 服务相关 */
  .service-form .el-button {
    border: none;
  }

  .service-form {
    margin-top: 20px;
  }

  /* 通用样式 */
  .input-icon {
    color: #409EFF;
    font-weight: bold;
  }

  .input-icon:hover {
    color: #66b1ff;
  }
</style>

<style>
  /* 覆盖框架原生样式  不可加scope */
  .add-goods .el-dialog__header {
    border-bottom: 1px solid #dcdfe6 !important;
  }

  .add-goods .el-table--enable-row-hover .el-table__body tr:hover > td {
    background: #fff;
  }

  .add-goods .el-table__row:hover {
    background: unset;
  }

  .item-title .el-tooltip {
    color: #666;
  }

  .add-goods .el-input__suffix-inner {
    line-height: 32px;
  }

  .add-goods .el-input--suffix .el-input__inner {
    padding-right: 40px;
  }

  .model-pic-uploader .el-upload--text {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px;
  }

  .select_img {
    width: 50px;
    height: 50px;
    line-height: 50px;
    border: 1px dashed #c0ccda;
    background-color: #fbfdff;
    font-size: 18px;
    color: #8c939d;
    cursor: pointer;
    border-radius: 6px;
    margin: 0 auto;
  }
</style>
